package com.hiveway.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.hiveway.constant.MessageConstant;
import com.hiveway.constant.PasswordConstant;
import com.hiveway.constant.StatusConstant;
import com.hiveway.context.BaseContext;
import com.hiveway.dto.EmployeeDTO;
import com.hiveway.dto.EmployeeLoginDTO;
import com.hiveway.dto.EmployeePageQueryDTO;
import com.hiveway.dto.PasswordEditDTO;
import com.hiveway.entity.Employee;
import com.hiveway.exception.AccountLockedException;
import com.hiveway.exception.AccountNotFoundException;
import com.hiveway.exception.PasswordErrorException;
import com.hiveway.mapper.EmployeeMapper;
import com.hiveway.result.PageResult;
import com.hiveway.service.EmployeeService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.List;

@Service
public class EmployeeServiceImpl implements EmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;

    /**
     * 员工登录
     *
     * @param employeeLoginDTO
     * @return
     */
    public Employee login(EmployeeLoginDTO employeeLoginDTO) {
        String username = employeeLoginDTO.getUsername();
        String password = employeeLoginDTO.getPassword();

        //1、根据用户名查询数据库中的数据
        Employee employee = employeeMapper.getByUsername(username);

        //2、处理各种异常情况（用户名不存在、密码不对、账号被锁定）
        if (employee == null) {
            //账号不存在
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        //密码比对
        //对前端传来的明文密码进行 md5 加密处理
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        if (!password.equals(employee.getPassword())) {
            //密码错误
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }

        if (employee.getStatus() == StatusConstant.DISABLE) {
            //账号被锁定
            throw new AccountLockedException(MessageConstant.ACCOUNT_LOCKED);
        }

        //3、返回实体对象
        return employee;
    }

    /**
     * 新增员工
     *
     * @param employeeDTO
     */
    @Override
    public void save(EmployeeDTO employeeDTO) {
//        传到持久层的数据建议使用实体类
        Employee employee = new Employee();
//        对象属性拷贝
        BeanUtils.copyProperties(employeeDTO, employee);
//        为剩余属性赋值
//        账号状态 1.正常；0.锁定，默认正常
        employee.setStatus(StatusConstant.ENABLE);
//        密码，默认 123456
        employee.setPassword(DigestUtils.md5DigestAsHex(PasswordConstant.DEFAULT_PASSWORD.getBytes()));
//        创建时间
        //employee.setCreateTime(LocalDateTime.now());
//        修改时间
        //employee.setUpdateTime(LocalDateTime.now());
//        创建人 id
        //employee.setCreateUser(BaseContext.getCurrentId());
//        修改人 id
        //employee.setUpdateUser(BaseContext.getCurrentId());

        employeeMapper.insert(employee);
    }

    /**
     * 员工分页查询
     *
     * @param employeePageQueryDTO
     * @return
     */
    @Override
    public PageResult pageQuery(EmployeePageQueryDTO employeePageQueryDTO) {
//        开始分页查询
        PageHelper.startPage(employeePageQueryDTO.getPage(), employeePageQueryDTO.getPageSize());
        Page<Employee> page = employeeMapper.pageQuery(employeePageQueryDTO);

        long total = page.getTotal();
        List<Employee> records = page.getResult();
        return new PageResult(total, records);
    }

    /**
     * 启用禁用员工账号
     *
     * @param status
     * @param id
     */
    @Override
    public void startOrStop(Integer status, Long id) {

//        创建实体类对象--1
//        Employee employee = new Employee();
//        employee.setStatus(status);
//        employee.setId(id);

//        创建实体类对象--2
        Employee employee = Employee.builder()
                .status(status)
                .id(id)
                .build();
        employeeMapper.update(employee);
    }

    /**
     * 根据id查询员工
     *
     * @param id
     */
    @Override
    public Employee getById(Long id) {
        Employee employee = employeeMapper.getById(id);
        employee.setPassword("******");
        return employee;
    }

    /**
     * 根据id修改员工
     *
     * @param employeeDTO
     */
    @Override
    public void update(EmployeeDTO employeeDTO) {
        Employee employee = new Employee();
        BeanUtils.copyProperties(employeeDTO, employee);

        //employee.setUpdateTime(LocalDateTime.now());
        //employee.setUpdateUser(BaseContext.getCurrentId());

        employeeMapper.update(employee);
    }

    /**
     * 修改密码
     *
     * @param passwordEditDTO
     */
    @Override
    public void updatePassword(PasswordEditDTO passwordEditDTO) {
        passwordEditDTO.setEmpId(BaseContext.getCurrentId());
//        获取原来的旧密码
        String originalOldPassword = employeeMapper.getOldPassword(passwordEditDTO);
//        获取录入的旧密码并加密
        String oldPassword = DigestUtils.md5DigestAsHex(passwordEditDTO.getOldPassword().getBytes());
        if (!oldPassword.equals(originalOldPassword)) {
//            旧密码输入错误
            throw new AccountLockedException(MessageConstant.PASSWORD_EDIT_FAILED) ;
        }
//        将新密码加密后再修改
        passwordEditDTO.setNewPassword(DigestUtils.md5DigestAsHex(passwordEditDTO.getNewPassword().getBytes()));
        employeeMapper.updatePassword(passwordEditDTO);
    }

}
